import { ActionContext } from 'vuex'
import { State, RootState } from '@vue/runtime-core'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { login, logout } from '@/api/auth'
import { getUserInfo } from '@/api/system/user'

interface LoginParam {
  usernameOrPhone: string,
  password: string,
  remberMe: boolean,
  verificationCode: string,
  // 验证码唯一标识
  uuid: string,
}
const user = {
  // 用户状态保存
  state: () => ({
    user: {},
    roles: [],
    token: getToken(),
    loadMenus: false
  }),
  // 改变状态,store.commit('increment')
  mutations: {
    SET_TOKEN: (state: State, token: string) => {
      state.token = token
    },
    SET_USER: (state: State, user: object) => {
      state.user = user
    },
    SET_ROLES: (state: State, roles: string[]) => {
      state.roles = roles
    },
    SET_LOAD_MENUS: (state: State, isLoadMenus: boolean) => {
      state.loadMenus = isLoadMenus
    }
  },
  // Action 提交的是 mutation，而不是直接变更状态
  // Action 可以包含任意异步操作
  actions: {
    async login(context: ActionContext<State, RootState>, loginParam: LoginParam) {
      const res: any = await login(loginParam)

      context.commit('SET_TOKEN', res.token)
      setToken(res.token, res.expiration)
      // 需要加载菜单
      context.commit('SET_LOAD_MENUS', true)
    },
    roles({ commit }: ActionContext<State, RootState>, roles: string[]) {
      commit('SET_ROLES', roles)
    },
    async getUserInfo({ commit }: ActionContext<State, RootState>) {
      const res = await getUserInfo()
      commit('SET_USER', res)
      localStorage.setItem("userID", res.id.toString());
      commit('SET_ROLES', res.authorities)
    },
    async logout(context: ActionContext<State, RootState>) {
      const res = await logout()
      clear(context)
    },
    clearUserData(context: ActionContext<State, RootState>) {
      clear(context)
    },

    // 修改是否加载菜单状态
    updateLoadMenus({ commit }: ActionContext<State, RootState>) {
      return new Promise<void>((resolve, reject) => {
        commit('SET_LOAD_MENUS', false)
        resolve()
        reject()
      })
    },
  },
  getters: {
    isLoadMenus: (state: State) => state.loadMenus,
    getUserInfo(state: State): {} {
      console.log('获取用户详情')
      return state.user;
    },
  }
}

const clear = (context: ActionContext<State, RootState>) => {
  context.commit('SET_TOKEN', '')
  context.commit('SET_USER', {})
  context.commit('SET_ROLES', [])
  removeToken()
}

export default user